import {Component, ElementRef, OnDestroy, OnInit, SimpleChange, ViewChild, ViewChildren} from '@angular/core';
import {DatePipe} from '@angular/common';
import {Router} from '@angular/router';
import {List} from 'linqts';
import {LimitedFarm} from './limited-farm';
import {LimitedFarmCategory, Term} from './limited-farm-category';
import {PlanPowerPanelComponent, PlantData, PlantDataItem} from './plan-power-panel/plan-power-panel.component';
import {WindPowerPanelComponent} from './wind-power-panel/wind-power-panel.component';
import {RealtimePowerPanelComponent} from './realtime-power-panel/realtime-power-panel.component';
//昨日损失电量
import {StopInfoStatistics} from '../../../entity/stopInfo-statistics.model';
import {StopInfoStatisticsService} from '../../../service/stopInfo-statistics.service';

import {TurbstatusColumn, TurbstatusData, TurbstatusPanelComponent, TurbstatusRow, TurbstatusTable} from './turbstatus-panel/turbstatus-panel.component';
import {TurboperPanelComponent} from './turboper-panel/turboper-panel.component';

import {TurbStatusService} from '../../../service/turbstatus.service';
import {FarmService} from '../../../service/farm.service';
import {FarmPlantPowerService} from '../../../service/farm-plant-power.service';
import {TurboperCategoryService} from '../../../service/turboper-category.service';

import {Farm} from '../../../entity/farm.model';
import {FarmPlantpower} from '../../../entity/farm-plant-power.model';
import {TurbStatus} from '../../../entity/turbstatus.model';
import {TagData} from '../../../entity/tag-data.model';
import {DataSourceService} from '../../../service/data-source/data-source.service';
import {ApplicationService} from '../../../service/application.service';
import {NzMessageService} from 'ng-zorro-antd';
import {FarmTotalTurbstatus} from './farm-total-turbstatus';

@Component({
  selector: 'app-main',
  templateUrl: './main.component.html',
  styleUrls: ['./main.component.css'],
  providers: [DataSourceService]
})
export class MainComponent implements OnInit, OnDestroy {
  /**
   * 定时查询风机操作
   *
   * @private
   * @type {*}
   * @memberof MainComponent
   */
  private turboperTotleTimer: any;

  /**
   * 定时查询风机操作
   *
   * @private
   * @type {*}
   * @memberof MainComponent
   */
  private Timer: any;

  /**
   * 查询损失电量时间
   *
   * @private
   * @type {*}
   * @memberof MainComponent
   */
  private date: Date = new Date();
  private dateTime: Date = new Date(
    this.date.getFullYear(),
    this.date.getMonth(),
    this.date.getDate() - 1
  );

  private stopInfoStatistics: StopInfoStatistics;

  /**
   * 风机状态数据统计和数据明细
   *
   * @type {TurbstatusData[]}@memberof MainComponent
   */
  public totalTurbstatusDatas: TurbstatusData[];
  public turbstatusTable: TurbstatusTable;
  private turbstatusRows: TurbstatusRow[] = [];
  /**
   * 逆变器状态数据统计和数据明细
   *
   * @type {TurbstatusData[]}
   * @memberof MainComponent
   */
  public totalInverterDatas: TurbstatusData[];
  public invertersTable: TurbstatusTable;
  private invertersRows: TurbstatusRow[] = [];
  /**
   * 风机操作数据统计和数据明细
   *
   * @type {TurbOperData[]}@memberof MainComponent
   */
  //public totalTurboperDatas: TurboperData[];
  //public turboperTable: TurbstatusTable;
  //private turboperRows: TurboperRow[] = [];

  /**
   * 总装机容量
   *
   * @memberof MainComponent
   */
  public generalCapacity: TagData;
  /**
   * 总有功功率
   *
   * @memberof MainComponent
   */
  public generalPower: TagData;
  /**
   * 总发电量
   *
   * @memberof MapComponent
   */
    // public generalPowerDay: TagData;
  public generalTPowerd: TagData;
  /**
   * 风场信息
   *
   * @type {Farm[]}@memberof MainComponent
   */
  public limitedFarms: LimitedFarm[] = [];
  /**
   * 当前选中风场信息
   *
   * @type {Farm}@memberof MainComponent
   */
  public currentLimitedFarm: LimitedFarm;

  /**
   * 日月年计划电量数据
   *
   * @type {PlantData}@memberof MainComponent
   */
  public dayPlantData: PlantData;
  public monthPlantData: PlantData;
  public yearPlantData: PlantData;

  /**
   *  实时发电量组件
   *
   * @type {ElementRef}@memberof SelectorComponent
   */
  @ViewChild('realtimePower', {static: true})
  realtimePower: RealtimePowerPanelComponent;
  /**
   *  风机状态统计组件
   *
   * @type {ElementRef}@memberof SelectorComponent
   */
  @ViewChildren('turbStatus')
  turbstatus: TurbstatusPanelComponent[];
  @ViewChild('dayPlan', {static: true})
  dayPlan: PlanPowerPanelComponent;
  @ViewChild('monthPlan', {static: true})
  monthPlan: PlanPowerPanelComponent;
  @ViewChild('yearPlan', {static: true})
  yearPlan: PlanPowerPanelComponent;

  /**
   * 风机操作
   *
   * @type {TurbstatusPanelComponent}@memberof MainComponent
   */
  @ViewChild('turbOper', {static: true})
  turbOper: TurboperPanelComponent;
  /**
   *  风功率
   *
   * @type {ElementRef}@memberof SelectorComponent
   */
  @ViewChild('windPower', {static: true})
  windPower: WindPowerPanelComponent;

  /**
   * 风机状态数量最大值
   *
   * @public
   * @type {number}@memberof MainComponent
   */

  /**
   * 公司地图配置，省份名称（广东：gd）
   *
   * @type {number}
   * @memberof MainComponent
   */
  @ViewChild('container', {static: true})
  private container: ElementRef;

  private mapUrl: string;

  public max: number = 1;
  /**
   * 倍率
   *
   * @public
   * @type {number}@memberof MainComponent
   */
  public ratio: number = 1;
  public timer: any = null;
  /**
   * 风场概览
   *
   * @type {*}
   * @memberof MainComponent
   */
  public winFarmCategory: any;
  /**
   * 光伏概览
   *
   * @type {*}
   * @memberof MainComponent
   */
  public pvCategory: any;
  /**
   * 总装机容量矫正
   *
   * @type {number}
   * @memberof MainComponent
   */
  public capacityCorrection: number = 0;

  /**
   *是否加载全部风场功率和发电量
   *
   * @memberof MainComponent
   */
  public isPowerAll = false;

  /**
   * Creates an instance of MainComponent.
   * @param {HistoryService} historyService
   * @param {FarmService} farmService
   * @param {TurboperCategoryService} turboperCategoryService
   * @param {TurbStatusService} TurbStatusService
   * @param {FarmPlantPowerService} farmPlantPowerService
   * @param {DatePipe} datePipe
   * @memberof MainComponent
   */
  constructor(
    private dataSource: DataSourceService,
    private application: ApplicationService,
    private farmService: FarmService,
    private TurbStatusService: TurbStatusService,
    private farmPlantPowerService: FarmPlantPowerService,
    private stopInfoStatisticsService: StopInfoStatisticsService,
    private datePipe: DatePipe,
    private _message: NzMessageService,
    private router: Router
  ) {
    const index = this.application.currentUserFarms.findIndex(
      farm => farm.farmCategory === 'photovoltaic'
    );
    if (index === -1) {
      //没有光伏的页面
      this.router.navigate(['/monitor/mainWinfarm']);
    }
    if (this.application.currentApplicationParams && this.application.currentApplicationParams['ratio']) {
      this.ratio = Number(this.application.currentApplicationParams['ratio'].paramValue);
    }
    if (
      this.application.currentMenuParams &&
      this.application.currentMenuParams['capacityCorrection']
    ) {
      this.capacityCorrection = Number(
        this.application.currentMenuParams.capacityCorrection.paramValue
      );
    }

    /*
    let mapName = this.application.appConfigData.appCompany;
    this.mapUrl = 'url(' + './assets/images/' + mapName + '.png' + ') no-repeat center'; */
  }

  ngOnInit(): void {
    //this._message.info('这是一条普通的提醒111111111111');
    this.initData();
    /*  this.renderer.setStyle(this.container.nativeElement, 'background', this.mapUrl);
     this.renderer.setStyle(this.container.nativeElement, 'background-size', 'auto 100%'); */
  }

  ngOnDestroy(): void {
    this.dataSource.dispose();
    if (this.turboperTotleTimer != null) {
      clearInterval(this.turboperTotleTimer);
    }
  }

  /**
   * 初始化数据
   *
   * @memberof MainComponent
   */
  private initData() {
    const id = this._message.loading('数据正在加载中', {nzDuration: 0})
      .messageId;
    let date = this.datePipe.transform(new Date(), 'yyyy-MM-dd');
    let farmGet = this.farmService.getFarmsWithTotalTurbineByUserId(
      this.application.currentUser.userId
    );
    let plantGet = this.farmPlantPowerService.getFarmPlantPowers();
    let turbStatusGet = this.TurbStatusService.getTurbStatus();
    let inverterStatusGet = this.TurbStatusService.getInverterStatus();
    let stopInfoStatisticsGet = this.stopInfoStatisticsService.getYesterDayPowerLoss(
      this.dateTime
    );
    let farmsListGet = this.farmService.getFarms();
    Promise.all([
      farmGet,
      plantGet,
      turbStatusGet,
      inverterStatusGet,
      stopInfoStatisticsGet,
      farmsListGet
    ]).then(res => {
      this._message.remove(id);
      if (res[0].length === res[5].length) {
        this.isPowerAll = true;
      }
      // 创建风场计划发电量模型
      // this.createFarmPlantPower(res[0], res[1].dayList, res[1].monthList, res[1].yearList);
      //创建风场分类
      this.createFarmCategory(res[0], res[4]);
      //创建风场数据模型
      this.createLimitedFarm(
        res[0],
        res[2],
        res[1].dayList,
        res[1].monthList,
        res[1].yearList,
        res[3]
      );
      //创建风机,逆变器状态统计模型
      this.totalTurbstatusDatas = this.createTotalStatusData(res[2]);
      this.totalInverterDatas = this.createTotalStatusData(res[3]);
      //创建风机状态表
      this.turbstatusTable = this.createStatusTable(
        this.limitedFarms,
        res[2],
        'winfarm'
      );

      //创建逆变器状态表
      this.invertersTable = this.createStatusTable(
        this.limitedFarms,
        res[3],
        'photovoltaic'
      );
      //创建风机操作统计模型
      //this.createTotalOperData(res[3]);
      //创建风机操作表
      //this.createOperTable(this.limitedFarms, res[3]);
    }).catch(error => {
      this._message.remove(id);
      if (this.application.appConfigData.isShowErr) {
        this._message.info('首页数据初始化失败' + error, {
          nzDuration: 3000
        });
      }
      //console.log('app-main initData has error', error);
    });
  }

  /**
   * 创建风场分类
   *
   * @private
   * @memberof MainComponent
   */
  private createFarmCategory(farms: Farm[], stopInfoStatistics: StopInfoStatistics[]) {
    //昨日损失电量
    let power = stopInfoStatistics.length ? stopInfoStatistics[0].lossPower * this.ratio : 0;
    //构建风场数据集合
    let list: List<Farm> = new List(farms);
    //按风场分类分组
    let groups = list.GroupBy(
      grouper => grouper.farmCategory,
      mapper => mapper
    );
    let categorys = Object.getOwnPropertyNames(groups);
    categorys.forEach(element => {
      let elementList = new List<Farm>(
        Object.getOwnPropertyDescriptor(groups, element).value
      );
      switch (element) {
        case 'winfarm':
          let winFarmCategory: LimitedFarmCategory = new LimitedFarmCategory(
            'winfarm',
            'turb.png',
            '#8fd8ab',
            '#dfffa6',
            '风场概览',
            [
              new Term(
                '装机容量',
                {
                  code: '',
                  value:
                  elementList.Sum(o => o.capacity) + this.capacityCorrection
                },
                'MW'
              ),
              new Term(
                '风场个数',
                {code: '', value: elementList.Count()},
                '个'
              ),
              new Term(
                '风机台数',
                {code: '', value: elementList.Sum(o => o.totalTurbine)},
                '台'
              ),
              new Term('有功功率', {code: '', value: 0}, 'MW'),
              new Term('平均风速', {code: '', value: 0}, 'm/s'),
              new Term('日发电量', {code: '', value: 0}, '万kWh')
              //增加昨日损失电量；
              // new Term('昨日损失电量', power, '万kWh')
            ]
          );
          this.winFarmCategory = winFarmCategory;
          break;
        case 'photovoltaic':
          let pvCategory: LimitedFarmCategory = new LimitedFarmCategory(
            'photovoltaic',
            'photovoltaic.png',
            '#ced88f',
            '#ffd075',
            '光伏概览',
            [
              new Term(
                '装机容量',
                {code: '', value: elementList.Sum(o => o.capacity)},
                'MW'
              ),
              new Term(
                '光伏电站个数',
                {code: '', value: elementList.Count()},
                '个'
              ),
              new Term(
                '逆变器个数',
                {code: '', value: elementList.Sum(o => o.totalTurbine)},
                '个'
              ),
              new Term('有功功率', {code: '', value: 0}, 'MW'),
              new Term('辐射量', {code: '', value: 0}, ' MJ/㎡'),
              new Term('日发电量', {code: '', value: 0}, '万kWh')
            ]
          );
          this.pvCategory = pvCategory;
          break;
      }
    });
  }

  /**
   * 创建风机状态统计数据
   *
   * @private
   * @param {TurbStatus[]} turbStatuies
   * @memberof MainComponent
   */
  private createTotalStatusData(turbStatuies: TurbStatus[]) {
    let totalTurbstatusDatas: TurbstatusData[] = [];
    //创建风场风机状态统计点
    turbStatuies.forEach(element => {
      let turbstatusData = new TurbstatusData();
      turbstatusData.id = element.statusId;
      turbstatusData.key = element.statusKey;
      turbstatusData.name = element.statusName;
      turbstatusData.color = element.statusColor;
      turbstatusData.value = 0;
      totalTurbstatusDatas.push(turbstatusData);
    });
    return totalTurbstatusDatas;
  }

  /**
   * 创建风机,逆变器状态明细表
   *
   * @private
   * @param {LimitedFarm[]} farms
   * @param {TurbStatus[]} turbStatuies
   * @memberof MainComponent
   */

  InverstatusRows: TurbstatusRow[] = [];

  private createStatusTable(
    farms: LimitedFarm[],
    turbStatuies: TurbStatus[],
    farmCategory: string
  ) {
    let title: string[];
    if (farmCategory == 'winfarm') {
      title = ['风场（台数）'];
    } else {
      title = ['光伏站（逆变器）'];
    }
    turbStatuies.forEach(element => {
      title.push(element.statusName);
    });
    farms.forEach(element => {
      if (element.farmCategory != farmCategory) return false;
      let tdRow = new TurbstatusRow();
      let tdColumn = new TurbstatusColumn(
        element.farmName + '（' + element.totalTurbine + '）'
      );
      tdRow.columns.push(tdColumn);
      if (farmCategory == 'winfarm') {
        element.farmTotalTurbstatuies.forEach(element => {
          let column = new TurbstatusColumn(element.data, element.color);
          tdRow.columns.push(column);
        });
        this.turbstatusRows.push(tdRow);
      } else if (farmCategory == 'photovoltaic') {
        element.farmTotalInverstatuies.forEach(element => {
          let column = new TurbstatusColumn(element.data, element.color);
          tdRow.columns.push(column);
        });
        this.InverstatusRows.push(tdRow);
      }
    });
    let turbstatusTable: TurbstatusTable = new TurbstatusTable();
    if (farmCategory == 'winfarm') {
      turbstatusTable.rows = this.turbstatusRows;
    } else if (farmCategory == 'photovoltaic') {
      turbstatusTable.rows = this.InverstatusRows;
    }
    turbstatusTable.title = title;
    // console.log(turbstatusTable)
    return turbstatusTable;
  }

  /**
   * 创建风机操作统计数据
   *
   * @private
   * @param {TurbStatus[]} turbStatuies
   * @memberof MainComponent
   */
  /*  private createTotalOperData(turboperCategories: TurboperCategory[]) {
     let totalTurboperDatas: TurboperData[] = [];
     //创建风场操作统计点
     turboperCategories.forEach(element => {
       let turbstatusData = new TurbstatusData();
       turbstatusData.id = element.operCategoryId;
       turbstatusData.key = element.operCategoryCode;
       turbstatusData.name = element.operCategoryName;
       turbstatusData.color = element.operCategoryColor;
       turbstatusData.value = 0;
       totalTurboperDatas.push(turbstatusData);
     });
     this.totalTurboperDatas = totalTurboperDatas;
   } */
  /**
   * 创建风机操作明细表
   *
   * @private
   * @param {LimitedFarm[]} farms
   * @param {TurbStatus[]} turbStatuies
   * @memberof MainComponent
   */

  /*  private createOperTable(farms: LimitedFarm[], turboperCategories: TurboperCategory[]) {
     let title: string[] = ['风场（台数）'];
     turboperCategories.forEach(element => {
       title.push(element.operCategoryName)
     });
     let turbstatusRows: TurbstatusRow[] = [];
     farms.forEach(element => {
       let tdRow = new TurbstatusRow();
       let tdColumn = new TurbstatusColumn(element.farmName + '（' + element.totalTurbine + '）');
       tdRow.columns.push(tdColumn);
       element.subState.forEach(element => {
         let column = new TurbstatusColumn(element.data, element.color);
         tdRow.columns.push(column);
       });
       turbstatusRows.push(tdRow);
     });
     this.turboperTable = new TurbstatusTable();

     this.turboperTable.rows = turbstatusRows;;
     this.turboperTable.title = title;

   } */

  getPlantModel(
    plantType: string,
    plantDatas: FarmPlantpower[],
    farm: Farm
  ): FarmPlantpower {
    let i = plantDatas.findIndex(o => o.farmId == farm.farmId);
    let plantData: FarmPlantpower;
    if (i > -1) {
      plantData = {
        plantPowerId: plantDatas[i].plantPowerId,
        farmId: farm.farmId,
        farmName: farm.farmName,
        plantType: plantType,
        datePlant: plantDatas[i].datePlant,
        plantPower: plantDatas[i].plantPower,
        completePower: null,
        adjustPower: plantDatas[i].adjustPower
      };
    } else {
      plantData = {
        plantPowerId: 0,
        farmId: farm.farmId,
        farmName: farm.farmName,
        plantType: plantType,
        datePlant: '',
        plantPower: 0,
        completePower: null,
        adjustPower: 0
      };
    }
    return plantData;
  }

  /**
   * 构建风场数据模型（构建实时数据点名 ，统计风场装机容量）
   * 并且调用推服务进行数据推送
   * @private
   * @param {Farm[]} farms
   * @param {PushService} pushService
   * @memberof MainComponent
   */
  private createLimitedFarm(
    farms: Farm[],
    turbStatuies: TurbStatus[],
    days: FarmPlantpower[],
    months: FarmPlantpower[],
    years: FarmPlantpower[],
    inverterStatus: TurbStatus[]
  ) {

    if (farms != null && farms.length > 0) {
      let historyCodes: string[] = [];
      const dq = this.application.tagDict['DQ001'];
      //const GriFPower = this.application.tagDict['GriFPower'];
      const companyCode = this.application.currentCompany.companyCode;

      const PowerDay = this.application.tagDict['PowerDay'];
      const CPowerd = this.application.tagDict['CPowerd'];
      const TPowerd = this.application.tagDict['TPowerd'];
      const WindSpeed = this.application.tagDict['MeanWindSpeed'];
      const Power = this.application.tagDict['Power'];
      const Communication = this.application.tagDict['Communication'];
      const PowerMonth = this.application.tagDict['PowerMonth'];
      const PowerYear = this.application.tagDict['PowerYear'];
      //辐射量测点
      const FSL = this.application.tagDict['radiation'];
      if (this.isPowerAll) {
        // this.generalPowerDay = this.dataSource.binding([companyCode], PowerDay);
        this.generalTPowerd = this.dataSource.binding([companyCode], TPowerd);
        this.generalPower = this.dataSource.binding([companyCode], Power);

        //有功
        this.winFarmCategory.terms[3].value = this.dataSource.binding(
          [companyCode, '1'],
          Power
        );
        //日发电量
        this.winFarmCategory.terms[5].value = this.dataSource.binding(
          [companyCode, '1'],
          PowerDay
          //CPowerd
        );
        if (this.pvCategory && this.pvCategory.terms && this.pvCategory.terms.length > 0) {
          this.pvCategory.terms[3].value = this.dataSource.binding(
            [companyCode, '2'],
            Power
          );
          this.pvCategory.terms[5].value = this.dataSource.binding(
            [companyCode, '2'],
            PowerDay
            // CPowerd
          );
        }
      } else {
        // this.generalPowerDay = {code: '', value: 0};
        this.generalTPowerd = {code: '', value: 0};
        this.generalPower = {code: '', value: 0};
        //有功
        this.winFarmCategory.terms[3].value = {code: '', value: 0};
        //日发电量
        this.winFarmCategory.terms[5].value = {code: '', value: 0};
        this.pvCategory.terms[3].value = {code: '', value: 0};
        this.pvCategory.terms[5].value = {code: '', value: 0};
      }

      let farmDay: FarmPlantpower[] = [];
      let farmMonth: FarmPlantpower[] = [];
      let farmYear: FarmPlantpower[] = [];
      farms.forEach(farm => {
        farmDay.push(this.getPlantModel('day', days, farm));
        farmMonth.push(this.getPlantModel('month', months, farm));
        farmYear.push(this.getPlantModel('year', years, farm));
      });
      let dayList = new List(farmDay);
      let tumbDayPlantData = new PlantData();
      tumbDayPlantData.totalCompletePower = 0;
      tumbDayPlantData.totalPlantPower = dayList.Sum(o => o.plantPower);

      let monthList = new List(farmMonth);
      let tumbMonthPlantData = new PlantData();
      tumbMonthPlantData.totalCompletePower = 0;
      tumbMonthPlantData.totalPlantPower = monthList.Sum(o => o.plantPower);

      let yearList = new List(farmYear);
      let tumbYearPlantData = new PlantData();
      tumbYearPlantData.totalCompletePower = 0;
      tumbYearPlantData.totalPlantPower = yearList.Sum(o => o.plantPower);
      let generalCapacity = 0;
      for (let index: number = 0; index < farms.length; index++) {
        let farm = farms[index];
        const farmCode = farm.farmCode.replace(/_1$/, '_3');
        //统计总装机容量
        generalCapacity += farm.capacity;
        //创建风场数据模型
        let limitedFarm = new LimitedFarm();
        this.limitedFarms.push(limitedFarm);
        limitedFarm.farmId = farm.farmId;
        limitedFarm.farmCode = farm.farmCode;
        limitedFarm.farmName = farm.farmName;
        limitedFarm.farmCategory = farm.farmCategory;
        limitedFarm.posx = farm.posx;
        limitedFarm.posy = farm.posy;
        limitedFarm.simpleCode = farm.simpleCode;
        limitedFarm.capacity = farm.capacity;
        limitedFarm.productionDate = farm.productionDate;
        limitedFarm.totalTurbine = farm.totalTurbine;
        limitedFarm.unShowName = farm.unShowName;

        //创建实时数据点
        limitedFarm.powerDay = this.dataSource.binding(
          [farm.farmCode],
          PowerDay
          // CPowerd
        );
        limitedFarm.PowerMonth = this.dataSource.binding(
          [farm.farmCode],
          PowerMonth
        );
        limitedFarm.PowerYear = this.dataSource.binding(
          [farm.farmCode],
          PowerYear
        );
        limitedFarm.totalPower = this.dataSource.binding(
          [farm.farmCode],
          Power
        );
        limitedFarm.communication = this.dataSource.binding(
          [farm.farmCode],
          Communication
        );
        limitedFarm.avgWindSpeed = null;
        limitedFarm.Irradiation = null;
        if (farm.farmCategory == 'winfarm') {
          limitedFarm.avgWindSpeed = this.dataSource.binding(
            [farm.farmCode],
            WindSpeed
          );
          historyCodes.push(limitedFarm.avgWindSpeed.code);
        } else if (farm.farmCategory == 'photovoltaic') {
          limitedFarm.Irradiation = this.dataSource.binding(
            [farm.farmCode],
            FSL
          );
          historyCodes.push(limitedFarm.Irradiation.code);
        }

        //添加点名用于查询历史数据
        let griFPowerCode = this.dataSource.buildTagCode([farmCode], dq);
        historyCodes.push(limitedFarm.totalPower.code);
        historyCodes.push(griFPowerCode);

        //创建风场历史数据
        limitedFarm.histories[griFPowerCode] = {
          code: griFPowerCode,
          title: '预测功率',
          data: [],
          color: '#C23531'
        };

        limitedFarm.histories[limitedFarm.totalPower.code] = {
          code: limitedFarm.totalPower.code,
          title: '有功功率',
          data: [],
          color: '#4B0082'
        };
        if (farm.farmCategory == 'winfarm') {
          limitedFarm.histories[limitedFarm.avgWindSpeed.code] = {
            code: limitedFarm.avgWindSpeed.code,
            title: '风速',
            data: [],
            color: '#7DC877'
          };
        } else if (farm.farmCategory == 'photovoltaic') {
          limitedFarm.histories[limitedFarm.Irradiation.code] = {
            code: limitedFarm.Irradiation.code,
            title: '辐射',
            data: [],
            color: '#7DC877'
          };
        }
        if (farm.farmCategory == 'winfarm') {
          //创建风场状态统计点
          turbStatuies.forEach(element => {
            let tagCode: string = element.statusKey + 'Count';
            let statusTag = this.application.tagDict[tagCode];
            limitedFarm.farmTotalTurbstatuies.push(
              new FarmTotalTurbstatus(
                element.statusId,
                element.statusKey,
                element.statusName,
                element.statusColor,
                this.dataSource.binding([farm.farmCode], statusTag)
              )
            );
          });
        } else if (farm.farmCategory == 'photovoltaic') {
          //创建逆变器状态统计点
          inverterStatus.forEach(element => {
            let tagCode: string = element.statusKey + 'Count';
            let statusTag = this.application.tagDict[tagCode];
            limitedFarm.farmTotalInverstatuies.push(
              new FarmTotalTurbstatus(
                element.statusId,
                element.statusKey,
                element.statusName,
                element.statusColor,
                this.dataSource.binding([farm.farmCode], statusTag)
              )
            );
          });
        }

        /* subState.forEach(element => {

          let tagCode: string = element.operCategoryKey + 'Count';
          let statusTag = this.application.tagDict[tagCode];
          let farmTotalTurbstatus: FarmTotalTurbstatus = new FarmTotalTurbstatus(
            element.operCategoryId,
            element.operCategoryKey,
            element.operCategoryName,
            element.operCategoryColor,
            this.dataSource.binding([farm.farmCode], statusTag));
            limitedFarm.subState.push(farmTotalTurbstatus);
        }) */
        let dayItem = new PlantDataItem();
        dayItem.id = farm.farmId;
        dayItem.name = farm.farmName;
        let farmDayPlantPower = dayList.FirstOrDefault(
          o => o.farmId == farm.farmId
        );
        if (farmDayPlantPower != null) {
          dayItem.plantPower = farmDayPlantPower.plantPower;
          dayItem.adjustPower = farmDayPlantPower.adjustPower;
          dayItem.completePower = limitedFarm.powerDay;
        }
        tumbDayPlantData.items.push(dayItem);

        let monthItem = new PlantDataItem();
        monthItem.id = farm.farmId;
        monthItem.name = farm.farmName;
        let farmMonthPlantPower = monthList.FirstOrDefault(
          o => o.farmId == farm.farmId
        );
        if (farmMonthPlantPower != null) {
          monthItem.plantPower = farmMonthPlantPower.plantPower;
          monthItem.adjustPower = farmMonthPlantPower.adjustPower;
          monthItem.completePower = limitedFarm.PowerMonth;
        }
        tumbMonthPlantData.items.push(monthItem);

        let yearItem = new PlantDataItem();
        yearItem.id = farm.farmId;
        yearItem.name = farm.farmName;
        let farmYearPlantPower = yearList.FirstOrDefault(
          o => o.farmId == farm.farmId
        );
        if (farmYearPlantPower != null) {
          yearItem.plantPower = farmYearPlantPower.plantPower;
          yearItem.adjustPower = farmYearPlantPower.adjustPower;
          yearItem.completePower = limitedFarm.PowerYear;
        }
        tumbYearPlantData.items.push(yearItem);
      }
      this.generalCapacity = {
        code: '',
        value: generalCapacity
      };
      this.dayPlantData = tumbDayPlantData;
      this.monthPlantData = tumbMonthPlantData;
      this.yearPlantData = tumbYearPlantData;

      this.realtimePower.ngOnChanges({
        farms: new SimpleChange(
          this.realtimePower.farms,
          this.limitedFarms,
          false
        )
      });
      //选中第一个风场
      this.currentLimitedFarm = this.limitedFarms[0];

      this.dataSource.begin().subscribe(next => {
          // console.log(next)
          this.totalGeneral();
          // let total = 0;
          this.dayPlantData.items.forEach((v, i) => {
            if (v.completePower && v.plantPower) {
              v.completiones = parseFloat((v.completePower.value / v.plantPower).toFixed(2)) * 100;
            } else {
              v.completiones = 0;
            }
            //v.completiones = v.completePower ? (parseFloat((v.completePower.value / v.plantPower).toFixed(2)))*100 : 0;
          });
          this.dayPlantData.totalCompletePower = this.generalTPowerd.value * this.ratio * 10000;
          // this.generalPowerDay.value / this.ratio;
          this.dayPlantData.totalCompletiones = parseFloat(((this.dayPlantData.totalCompletePower / this.dayPlantData.totalPlantPower) * 100).toFixed(2));
          let total = 0;
          this.monthPlantData.items.forEach((v, i) => {
            total += v.completePower ? v.completePower.value + v.adjustPower : 0 + v.adjustPower;
            if (v.completePower && v.plantPower) {
              v.completiones = parseFloat((v.completePower.value / v.plantPower).toFixed(2)) * 100;
            } else {
              v.completiones = 0;
            }
          });
          this.monthPlantData.totalCompletePower = total;
          // tslint:disable-next-line:max-line-length
          this.monthPlantData.totalCompletiones = parseFloat(
            ((this.monthPlantData.totalCompletePower / this.monthPlantData.totalPlantPower) * 100
            ).toFixed(2)
          );

          total = 0;
          this.yearPlantData.items.forEach((v, i) => {
            total += v.completePower ? v.completePower.value : 0 + v.adjustPower;
            if (v.completePower && v.plantPower) {
              v.completiones = parseFloat((v.completePower.value / v.plantPower).toFixed(2)) * 100;
            } else {
              v.completiones = 0;
            }
          });
          this.yearPlantData.totalCompletePower = total;
          // tslint:disable-next-line:max-line-length
          this.yearPlantData.totalCompletiones = parseFloat(
            (
              (this.yearPlantData.totalCompletePower /
                this.yearPlantData.totalPlantPower) *
              100
            ).toFixed(2)
          );
          this.dayPlan.changeData();
          this.monthPlan.changeData();
          this.yearPlan.changeData();

        },
        error => {
          if (this.application.appConfigData.isShowErr) {
            this._message.info('首页实时数据' + error, {nzDuration: 3000});
          }
        }
      );

      //查询历史数据
      let start: Date = new Date(new Date().toLocaleDateString());
      let end: Date = new Date(
        new Date(new Date().toLocaleDateString()).getTime() + 172800000
      );
      this.dataSource.history.getHistoriesWithTimer(10 * 60, historyCodes, start, end, 10 * 60).subscribe(
        next => {
          let list = new List(next);
          let groups = list.GroupBy(
            grouper => grouper.code,
            mapper => mapper
          );
          let codes = Object.getOwnPropertyNames(groups);
          codes.forEach(code => {
            let valueObj = Object.getOwnPropertyDescriptor(groups, code).value;
            this.limitedFarms.forEach(farm => {
              if (farm.histories[code] != null) {
                let valuelist = new List<TagData>(valueObj);
                farm.histories[code].data = [];
                valuelist.ForEach(el => {
                  farm.histories[code].data.push([el.time, el.value.toFixed(2)]);
                });
              }
            });
          });
          this.windPower.update();
        },
        error => {
          if (this.application.appConfigData.isShowErr) {
            this._message.info('历史数据' + error, {nzDuration: 3000});
          }

          //console.log('app-main createLimitedFarm has error', error);
        }
      );
    }
  }

  /**
   * 统计信息
   *
   * @private
   * @memberof MainComponent
   */
  private totalGeneral() {
    if (this.limitedFarms != null && this.limitedFarms.length > 0) {
      let list: List<LimitedFarm> = new List<LimitedFarm>(this.limitedFarms);
      // if (!this.isPowerAll) {
      //统计总实时发电量
      this.generalTPowerd.value = list.Sum(o => o.powerDay.value);
      //统计总有功能功率
      this.generalPower.value = list.Sum(o => o.totalPower.value);
      // }
      //按风场分类进行统计
      this.totalCategory(list);
      //统计所有风场个风机状态数量
      this.totalTurbstatus(list);
      this.realtimePower.ngOnChanges({
        farms: new SimpleChange(
          this.realtimePower.farms,
          this.limitedFarms, false
        )
      });
    }
  }

  /**
   * 统计各类风场信息
   *
   * @private
   * @param {List<LimitedFarm>} list
   * @memberof MainComponent
   */
  private totalCategory(list: List<LimitedFarm>) {
    //按风场分类分组
    let groups = list.GroupBy(
      grouper => grouper.farmCategory,
      mapper => mapper
    );
    //获取分类名称集合
    let categorys = Object.getOwnPropertyNames(groups);
    //按分类名称进行统计
    categorys.forEach(element => {
      let elementList = new List<LimitedFarm>(
        Object.getOwnPropertyDescriptor(groups, element).value
      );
      let totalCompanyTurbs = elementList.Sum(o => o.totalTurbine);
      // if (this.isPowerAll) {
      //   switch (element) {
      //     case 'winfarm':
      //       this.winFarmCategory.terms[4].value.value =
      //         elementList.Sum(o => o.avgWindSpeed.value * o.totalTurbine) /
      //         totalCompanyTurbs;
      //       break;
      //     case 'photovoltaic':
      //       this.pvCategory.terms[4].value.value = elementList.Sum(
      //         o => o.Irradiation.value
      //       );
      //       break;
      //   }
      // } else {
      switch (element) {
        case 'winfarm':
          this.winFarmCategory.terms[3].value.value = elementList.Sum(
            o => o.totalPower.value
          );
          this.winFarmCategory.terms[4].value.value =
            elementList.Sum(o => o.avgWindSpeed.value * o.totalTurbine) /
            totalCompanyTurbs;
          this.winFarmCategory.terms[5].value.value =
            elementList.Sum(o => o.powerDay.value);
          break;
        case 'photovoltaic':
          this.pvCategory.terms[3].value.value = elementList.Sum(o => o.totalPower.value);
          this.pvCategory.terms[5].value.value = elementList.Sum(o => o.powerDay.value);
          this.pvCategory.terms[4].value.value = elementList.Sum(o => o.Irradiation.value);
          break;
      }
      // }
    });
  }

  /**
   * 统计风场风机状态
   *
   * @private
   * @param {List<LimitedFarm>} list
   * @memberof MainComponent
   */
  private totalTurbstatus(list: List<LimitedFarm>) {
    let all = new List<FarmTotalTurbstatus>();
    let allForm = list.Select(o => o.farmTotalTurbstatuies);
    allForm.ForEach(element => {
      all.AddRange(element);
    });
    this.totalTurbstatusDatas.forEach(element => {
      //统计所有风场下相应的风机状态数量
      element.value = all.Where(o => o.id == element.id).Sum(o => o.data.value);
    });
    //逆变器状态
    all = new List<FarmTotalTurbstatus>();
    allForm = list.Select(o => o.farmTotalInverstatuies);
    allForm.ForEach(element => {
      all.AddRange(element);
    });
    this.totalInverterDatas.forEach(element => {
      //统计所有风场下相应的风机状态数量
      element.value = all.Where(o => o.id == element.id).Sum(o => o.data.value);
    });
    /* all = new List<FarmTotalTurbstatus>();
    allForm = list.Select(o => o.subState);
    allForm.ForEach(element => {
      all.AddRange(element);
    });
    this.totalTurboperDatas.forEach(element => {

      //统计所有风场下相应的风机状态数量
      element.value = all
        .Where(o => o.id == element.id)
        .Sum(o => o.data.value);
    });
    let max = 1;
    this.totalTurboperDatas.forEach(v => {
      if (v.value > max) {
        max = v.value
      }
    })
    this.max = max; */
    this.turbstatus.forEach((elem, i) => {
      elem.updateEchart();
    });
  }

  /**
   * 风场选中项发生变化
   *
   * @param {Farm} data
   * @memberof MainComponent
   */
  onChangeFarm(data: LimitedFarm) {
    this.currentLimitedFarm = data;
  }

  ondblclick(ev) {
    this.router.navigate(['/monitor/capacity']);
  }
}
